import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classnames from 'classnames'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router-dom'

export default function Login() {
	const [time, setTime] = useState(0)
	const history = useHistory()
	const location = useLocation()
	const dispatch = useDispatch()

	const formik = useFormik({
		initialValues: {
			mobile: '13700001111',
			code: '246810'
		},

		validationSchema: Yup.object().shape({
			mobile: Yup.string().required('请输入手机号').matches(/^1[3456789]\d{9}$/, '手机号格式错误'),
			code: Yup.string().required('请输入验证码').matches(/^\d{6}$/, '验证码6个数字')
		}),

		onSubmit: async (values) => {
			// 内部实现了禁止跳转
			await dispatch(login(values))
			Toast.success('登录成功')
			if(location.state) {
				history.replace(location.state.from)
			}else {
				history.push('/home')
			}

		}
	})

	const send = async () => {
		if(time > 0)  return

		// 发送验证码时先确定是否输入手机号, 手机号获取焦点
		if(!/^1[3456789]\d{9}$/.test(formik.values.mobile)) {
			formik.setTouched({
				mobile: true
			})
			return
		}

		// dispath也是异步的
		await dispatch(sendCode(mobile))
		Toast.success('验证码发送成功', 1);

		// 开启倒计时
		setTime(5)
		let timeId = setInterval(() => {
			setTime(time => {
				if(time === 1) {
					clearInterval(timeId)
				}
				return time - 1
			})
			
		}, 1000)
	}

	const { values: {mobile, code}, handleSubmit, handleChange, handleBlur, errors, touched } = formik
	return (
		<div className={styles.root}>
			<NavBar></NavBar>

			<div className="content">
				<h3>短信登录</h3>

				<form onSubmit={ handleSubmit }>
					<div className="input-item">
						<Input type="text" placeholder="请输入手机号" name="mobile"  onChange={ handleChange } onBlur={handleBlur}
							value={ mobile }/>

						{errors.mobile && touched.mobile && (
							<div className="validate">{errors.mobile}</div>
						)}
					</div>
					<div className="input-item">
						<Input extra={time === 0 ? '获取验证码': time + 's后获取'} placeholder='请输入验证码' onExtraClick={ send } name="code" 
							onBlur={handleBlur} onChange={ handleChange } value={ code }/>

						{errors.code && touched.code && (
							<div className="validate">{errors.code}</div>
						)}
					</div>
					<button type='submit' className={classnames('login-btn', formik.isValid ? '' : 'disabled')}
  						disabled={!formik.isValid}>登录</button>
				</form>
			</div>

		</div>
	)
}
